package com.rn.gypsophila.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description: 心跳处理器
 *
 * @author 然诺
 * @date 2021/04/20
 */
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private AtomicInteger unRecPingTimes = new AtomicInteger(1);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = (String) msg;
        // 接收客户端心跳信息
        if (message.contains("heartbeat")) {
            //清零心跳失败计数器
            unRecPingTimes = new AtomicInteger(1);
            log.info("server receive client[" + ctx.channel().id() + "] ping msg :---->" + message);
            //接收客户端心跳后,进行心跳响应
            String pong = "heartbeat:pong\n";
            ctx.channel().writeAndFlush(pong);
            ReferenceCountUtil.release(msg);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    /**
     * 事件触发器，该处用来处理客户端空闲超时,发送心跳维持连接。
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                log.warn("===服务器端===(READER_IDLE 读超时)");
                unRecPingTimes.getAndIncrement();
                // 客户端未进行ping心跳发送的次数等于3,断开此连接
                if (unRecPingTimes.intValue() == 3) {
                    ctx.disconnect();
                    log.warn("此客户端连接超时，服务器主动关闭此连接....");
                }
            } else if (event.state() == IdleState.WRITER_IDLE) {
                log.warn("===服务器端===(WRITER_IDLE 写超时)");

            } else if (event.state() == IdleState.ALL_IDLE) {
                log.warn("===服务器端===(ALL_IDLE 总超时)");
            }
        }
        super.userEventTriggered(ctx, evt);
    }

}